﻿window.ArthurGraus = window.ArthurGraus || {};

var spoe;
/*
$(document).ready(function () {
    spoe = new ArthurGraus.SharePointPermissionExplorer();
    spoe.initialize();
});*/
function StartApp() {
    spoe = new ArthurGraus.SharePointPermissionExplorer();
    spoe.initialize();
}

ArthurGraus.SharePointPermissionExplorer = function () {
    var mainself = this;
    var adRotator = new ArthurGraus.AdRotator('SPPE', 10000, 'adRotator', 1);
    var analytics = new ArthurGraus.Analytics('SPPE');
    var mainViewModel = new ViewModel();
    var waitDialog = null;
    
    mainself.Wait = function () {
        waitDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose(SP.Res.dialogLoading15);
    }
    mainself.CancelWait = function () {
        waitDialog.close();
    }
    mainself.initialize = function () {
        adRotator.initialize();
        analytics.initialize();
        mainViewModel.initialize();
        ko.applyBindings(mainViewModel);
    }
    function List(listObject) {
        var self = this;
        self.type = "List";
        self.listObject = listObject;
        self.id = listObject.get_id();
        self.title = listObject.get_title();
        self.hasUniqueRoleAssignment = ko.observable(false);
        self.roleAssignments = ko.observableArray();
        self.memberRoleCollection = ko.observableArray();
        self.formattedName = ko.computed(function () {
            var finalName = "  " + self.title;
            return finalName;
        });
        self.InheriteImgSources = ko.computed(function () {
            if (self.hasUniqueRoleAssignment()) {
                return "../Images/Inherite.png";
            }
            else
                return "../Images/StopInheriting.png";
        });
        self.InheriteImgTip = ko.computed(function () {
            if (self.hasUniqueRoleAssignment()) {
                return "Click to inherit permissions from the parent Web site";
            }
            else
                return "Click to create unique permissions for this list";
        });
    }

    function Library(libraryObject) {
        var self = this;
        self.type = "Library";
        self.libraryObject = libraryObject;
        self.id = libraryObject.get_id();
        self.title = libraryObject.get_title();
        self.hasUniqueRoleAssignment = ko.observable(false);
        self.roleAssignments = ko.observableArray();
        self.memberRoleCollection = ko.observableArray();
        self.formattedName = ko.computed(function () {
            var finalName = "  " + self.title;
            return finalName;
        });
        self.InheriteImgSources = ko.computed(function () {
            if (self.hasUniqueRoleAssignment()) {
                return "../Images/Inherite.png"
            }
            else
                return "../Images/StopInheriting.png"
        });
        self.InheriteImgTip = ko.computed(function () {
            if (self.hasUniqueRoleAssignment()) {
                return "Click to inherit permissions from the parent Web site";
            }
            else
                return "Click to create unique permissions for this library";
        });
    }
    function Site(site, imgSource) {
        var self = this;
        self.type = "Site";
        self.site = site;
        self.id = site.get_id();
        self.title = site.get_title();
        self.imgSource = ko.observable(imgSource);
        self.imgSourcelist = ko.observable(imgSource);
        self.imgSourcelibrary = ko.observable(imgSource);
        self.imgSourcesubSite = ko.observable(imgSource);
        self.hasUniqueRoleAssignment = ko.observable(false);
        self.collectionCount = 0;
        self.itemCollection = null;
        self.softedItemCollection = new Array();
        self.listlvl2 = String(self.id) + "list2";
        self.librarylvl2 = String(self.id) + "library2";
        self.subSitelvl2 = String(self.id) + "subSite2";
        self.lists = ko.observableArray();
        self.libraries = ko.observableArray();
        self.roleAssignments = ko.observableArray();
        self.subSites = ko.observableArray();
        self.memberRoleCollection = ko.observableArray();
        self.formattedName = ko.computed(function () {
            var finalName = "  " + self.title;
            return finalName;
        });
        self.InheriteImgSources = ko.computed(function () {
            if (self.hasUniqueRoleAssignment()) {
                return "../Images/Inherite.png"
            }
            else
                return "../Images/StopInheriting.png"
        });
        self.InheriteImgTip = ko.computed(function () {
            if (self.hasUniqueRoleAssignment()) {
                return "Click to inherit permissions from the parent Web site";
            }
            else
                return "Click to create unique permissions for this Site";
        });
    }

    function Principal(principal,type) {
        var self = this;
        self.principal = principal;
        self.id = principal.get_id();
        self.title = principal.get_title();
        self.type = type;
        self.formattedName = ko.computed(function () {
            var finalName = "";
            var testName = self.title;
            var numstring = self.title.length;
            for (var a = 0; a < numstring; a++) {
                finalName += testName.substr(a * 1, 1) + " ";
            }
            return testName;
        });
    }

    function AvailableRole(role) {
        var self = this;
        self.role = role;
        self.roleEnable = ko.observable(false);
        self.getDescription = ko.computed(function () {
            var Description = self.role.get_name();
            try {
                Description += " - " + self.role.get_description();
            }
            catch (err) {
                return Description;
            }
            return Description;
        })
        self.NotLimittedAcess = ko.computed(function () {
            if (self.role.get_roleTypeKind() != 1)
                return true;
            else
                return false;
        })

    }


    function RoleAssignment(principal) {
        var self = this;
        self.roles = ko.observableArray();
        self.principal = ko.observable(principal);
        self.getTooltips = ko.computed(function () {
            var finalRole = "";
            var tooltip = "\n--------------------------------------------------------";
            for (var count in self.roles()) {
                if (finalRole.length == 0)
                    finalRole = self.roles()[count].get_name();
                else
                    finalRole += " + " + self.roles()[count].get_name();
            }
            for (var count in self.roles()) {
                tooltip += "\n" + self.roles()[count].get_name();
                try {
                    tooltip += " - " + self.roles()[count].get_description();
                }
                catch (err) {
                }
            }
            finalRole += tooltip;
            return finalRole;
        })
        self.formattedRole = ko.computed(function () {
            var finalRole = "";
            for (var count in self.roles()) {
                if (finalRole.length == 0)
                    finalRole = self.roles()[count].get_name().substring(0, 1);
                else
                    finalRole += "+" + self.roles()[count].get_name().substring(0, 1);
            }

            return finalRole;
        });
    }

    function ViewModel() {
        var self = this;
        var item = null;
        var siteName = "";
        var currentSelection = null;
        var itemCollection = new Array();
        var SiteID = null;
        var listSaver = new Array();
        var valueLoading = false;
        var hasPrinciple = true;
        var temporaryObject = null;
        self.sysLoading = ko.observable(false);
        self.showList = ko.observable(false);
        self.showLibrary = ko.observable(true);
        self.showUsers = ko.observable(false);
        self.showGroups = ko.observable(true);
        self.FullControl = ko.observable(false);
        self.Inheritance = ko.observable(false);
        self.Design = ko.observable(false);
        self.Edit = ko.observable(false);
        self.Contribute = ko.observable(false);
        self.Read = ko.observable(false);
        self.ViewOnly = ko.observable(false);
        self.RestrictedInterfacesforTranslation = ko.observable(false);
        self.Approve = ko.observable(false);
        self.ManageHierarchy = ko.observable(false);
        self.RestrictedRead = ko.observable(false);
        self.LimitedAccess = ko.observable(false);
        self.showUniqueAssignments = ko.observable(true);
        self.hostWebUrl = "";
        self.appWebContext = null;
        self.hostWebContext = null;
        self.hostWeb = null;
        self.itemCollection = null;
        //self.userCollection = null;
        //self.groupCollection = null;
        self.roles = null;
        self.subSiteCollection = null;
        self.permissionlvl = null;
        self.test = null;
        self.imgSource = ["../Images/plus.png", "../Images/minus.png"];
        self.temporaryObject = null;
        self.temporaryPrincipal = null;
        self.siteCollection = ko.observableArray();
        self.principleCollection = ko.observableArray();
        self.userPrinciples = ko.observableArray();
        self.groupPrinciples = ko.observableArray();
        self.roleCollection = ko.observableArray();
        self.NewRolesCollection = new Array();
        //self.usersCollection = ko.observableArray();
        //self.groupsCollection = ko.observableArray();
        self.initialize = function () {
            
            self.hostWebUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
            self.appWebContext = new SP.ClientContext.get_current();
            self.hostWebContext = new SP.AppContextSite(self.appWebContext, self.hostWebUrl);
            self.hostWeb = self.hostWebContext.get_web();
            self.groupCollection = self.hostWeb.get_siteGroups();
            self.userCollection = self.hostWeb.get_siteUsers();
            item = self.hostWeb;
            self.appWebContext.load(item);
            self.appWebContext.load(self.groupCollection);
            self.appWebContext.load(self.userCollection);
            self.appWebContext.executeQueryAsync(self.onGetSiteName, self.onError);
            self.roles = self.hostWebContext.get_web().get_roleDefinitions();
            self.appWebContext.load(self.roles);
            self.appWebContext.executeQueryAsync(self.onGetRoleDefinitions, self.onError);
            $("#divChangePermission").hide();
        }
        
        self.onGetRoleDefinitions = function () {
            var itemEnumerator = self.roles.getEnumerator();
            while (itemEnumerator.moveNext()) {
                self.roleCollection.push(new AvailableRole(itemEnumerator.get_current()));
                //self.roleCollection.push(itemEnumerator.get_current());
            }


        }

        self.onGetSiteName = function () {
            self.siteCollection.push(new Site(item, self.imgSource[0]));
            self.siteCollection()[0].hasUniqueRoleAssignment(true);
            self.appWebContext.load(self.siteCollection()[0].site, 'RoleAssignments');
            self.appWebContext.executeQueryAsync(self.onGetMemberAndRoleOfSite, self.onError);
            var itemEnumerator = self.userCollection.getEnumerator();
            itemCollection = [];
            while (itemEnumerator.moveNext()) {
                itemCollection.push(itemEnumerator.get_current());
            }
            itemCollection.sort(function (a, b) {
                var nameA = String(a.get_title()).toLowerCase(), nameB = String(b.get_title()).toLowerCase();
                if (nameA < nameB)
                    return -1;
                if (nameA > nameB)
                    return 1;
                return 0;
            });
            for (var count in itemCollection) {
                self.principleCollection.push(new Principal(itemCollection[count], "User"));
            }
            itemEnumerator = self.groupCollection.getEnumerator();
            itemCollection = [];
            while (itemEnumerator.moveNext()) {
                itemCollection.push(itemEnumerator.get_current());
            }
            itemCollection.sort(function (a, b) {
                var nameA = String(a.get_title()).toLowerCase(), nameB = String(b.get_title()).toLowerCase();
                if (nameA < nameB)
                    return -1;
                if (nameA > nameB)
                    return 1;
                return 0;
            });
            for (var count in itemCollection) {
                self.principleCollection.push(new Principal(itemCollection[count], "Group"));
            }
            self.checkGroupandUserEnable();
        }

        self.onGetMemberAndRoleOfSite = function () {
            self.siteCollection()[0].collectionCount==0
            var itemEnumerator = self.siteCollection()[0].site.get_roleAssignments().getEnumerator();
            while (itemEnumerator.moveNext()) {
                self.siteCollection()[0].collectionCount++;
            }
            itemEnumerator = self.siteCollection()[0].site.get_roleAssignments().getEnumerator();
            while (itemEnumerator.moveNext()) {
                self.siteCollection()[0].memberRoleCollection.push(itemEnumerator.get_current());
                var length = self.siteCollection()[0].memberRoleCollection().length;
                self.appWebContext.load(self.siteCollection()[0].memberRoleCollection()[length - 1], 'Member');
                self.appWebContext.load(self.siteCollection()[0].memberRoleCollection()[length - 1], 'RoleDefinitionBindings');
                self.appWebContext.executeQueryAsync(self.AssigntValueSite, self.onError);
            }
        }

        self.AssigntValueSite = function () {
            self.siteCollection()[0].collectionCount--;
            if (self.siteCollection()[0].collectionCount == 0) {
                for (var countRole in self.siteCollection()[0].memberRoleCollection()) {
                    var itemEnumerator = self.siteCollection()[0].memberRoleCollection()[countRole].get_roleDefinitionBindings().getEnumerator();
                    self.siteCollection()[0].roleAssignments.push(new RoleAssignment(self.siteCollection()[0].memberRoleCollection()[countRole].get_member().get_title()));
                    while (itemEnumerator.moveNext()) {
                        var length = self.siteCollection()[0].roleAssignments().length;
                        self.siteCollection()[0].roleAssignments()[length - 1].roles.push(itemEnumerator.get_current());
                    }
                }
            }
        }

        self.onError = function (sender, args) {
            alert('Request failed. ' + args.get_message() +
            '\n' + args.get_stackTrace());
            self.sysLoading(false);
            mainself.CancelWait();
        }
        self.libraryNavigator = function (e) {
            currentSelection = e;
            //self.onCheckAll();
            //self.checkGroupandUserEnable();
            //self.checkUniqueAssignments();
            if (currentSelection.imgSourcelibrary() == self.imgSource[0]) {
                $("#" + currentSelection.librarylvl2).show();
                currentSelection.imgSourcelibrary(self.imgSource[1]);
            }
            else{
                $("#" + currentSelection.librarylvl2).hide();
                currentSelection.imgSourcelibrary(self.imgSource[0]);
            }
        }
        self.listNavigator = function (e) {
            currentSelection = e;
            //self.onCheckAll();
            //self.checkGroupandUserEnable();
            //self.checkUniqueAssignments();
            if (currentSelection.imgSourcelist() == self.imgSource[0]) {
                $("#" + currentSelection.listlvl2).show();
                currentSelection.imgSourcelist(self.imgSource[1]);
            }
            else {
                $("#" + currentSelection.listlvl2).hide();
                currentSelection.imgSourcelist(self.imgSource[0]);
            }
        }
        self.subSiteNavigator = function (e) {
            currentSelection = e;
            //self.checkGroupandUserEnable();
            //self.checkUniqueAssignments();
            if (currentSelection.imgSourcesubSite() == self.imgSource[0]) {
                $("#" + currentSelection.subSitelvl2).show();
                currentSelection.imgSourcesubSite(self.imgSource[1]);
            }
            else {
                $("#" + currentSelection.subSitelvl2).hide();
                currentSelection.imgSourcesubSite(self.imgSource[0]);
            }
        }
        self.getPrincipalRole = function (principal,object) {
            
                try {
                    for (var count in object.roleAssignments()) {
                        if (object.roleAssignments()[count].principal() == principal.get_title()) {
                            if (object.roleAssignments()[count].formattedRole().length > 3)
                                return "...";
                            else
                            return object.roleAssignments()[count].formattedRole();
                        }
                    }
                }
            catch (err) {
                return "";
                }
                return "";
        };
        self.getTip = function (principal, object) {
            var finaltip = "";
            try {
                for (var count in object.roleAssignments()) {
                    if (object.roleAssignments()[count].principal() == principal.get_title()) {
                        finaltip = object.roleAssignments()[count].getTooltips();
                        return finaltip;
                    }
                }
            }
            catch (err) {
                return "";
            }
            return "";
        };

        self.onChangePermission = function (object, principal) {
            
            self.resetRoles();
            self.temporaryObject = object;
            self.temporaryPrincipal = principal;
            if (self.temporaryObject.type == "List")
                temporaryObject = self.temporaryObject.listObject;
            if (self.temporaryObject.type == "Library")
                temporaryObject = self.temporaryObject.libraryObject;
            if (self.temporaryObject.type == "Site")
                temporaryObject = self.temporaryObject.site;
            if (self.temporaryObject.hasUniqueRoleAssignment())
                self.Inheritance(false);
            else
                self.Inheritance(true);
            try {
                for (var count in object.roleAssignments()) {
                    if (object.roleAssignments()[count].principal() == principal.principal.get_title()) {
                        for (var num in object.roleAssignments()[count].roles()) {
                            for (var a in self.roleCollection()) {
                                if (object.roleAssignments()[count].roles()[num].get_name() == self.roleCollection()[a].role.get_name()) {
                                    self.roleCollection()[a].roleEnable(true);
                                }
                            }
                        }
                    }
                }
            }
            catch (err) {
            }
            $("#divChangePermission").show();
            
        }

        self.onActivate = function () {
            RegisterNewKey("573F-E766-BE97-4507", "TOM", "Email", "SharePoint Permission Explorer");
        }
        
        self.onApplyChangePermission = function () {
            mainself.Wait();
            //if (PaidVersion == true) {

            self.NewRolesCollection = [];
            for (var a in self.roleCollection()) {
                if (self.roleCollection()[a].roleEnable()) {
                    self.AddNewRole(self.roleCollection()[a]);
                }
            }
            try {
                if (self.getPrincipalRole(self.temporaryPrincipal.principal, self.temporaryObject) == "" && self.NewRolesCollection.length != 0) {
                    //mainself.Wait();
                    hasPrinciple = false;
                    self.sysLoading(true);
                    self.ChangeRoleAssignment();
                }
                else {
                    for (var count in self.temporaryObject.roleAssignments()) {
                        if (self.temporaryObject.roleAssignments()[count].principal() == self.temporaryPrincipal.principal.get_title()) {

                            if (self.checkRoleSimilarity(self.temporaryObject.roleAssignments()[count].roles(), self.NewRolesCollection)) {
                                //mainself.CancelWait();
                            }
                            else {
                                //mainself.Wait();
                                hasPrinciple = true;
                                self.sysLoading(true);
                                self.ChangeRoleAssignment();
                            }

                        }
                    }
                }
            }
            catch (err) {
                mainself.CancelWait();
            }
            if (!hasPrinciple) {
                mainself.CancelWait();
            }
            $("#divChangePermission").hide();
            //}
            /*else {
                
                    var r = confirm("You are using the free version, which do not have function to change the permission, would you like to buy our full version for 10 euro?");
                if (r == true) {
                    window.location.href = 'http://www.arthurgraus.nl/Pages/SharePointPermissionExplorer.aspx';

                }
                else {
                }
            }*/

        }
        self.ChangeRoleAssignment = function () {
            if (temporaryObject != self.siteCollection()[0].site)
                temporaryObject.breakRoleInheritance(true);
            if (hasPrinciple == false) {
                var collRoleDefinitionBinding = SP.RoleDefinitionBindingCollection.newObject(self.appWebContext);
                for (var num in self.NewRolesCollection) {
                    if (self.NewRolesCollection[num].NotLimittedAcess())
                        collRoleDefinitionBinding.add(self.NewRolesCollection[num].role);
                }
                temporaryObject.get_roleAssignments().add(self.temporaryPrincipal.principal, collRoleDefinitionBinding);
                self.appWebContext.load(self.temporaryPrincipal.principal);
                self.appWebContext.load(temporaryObject);
                self.appWebContext.executeQueryAsync(self.finishAddRoles, self.onError);
            }
            else if (self.NewRolesCollection.length > 0) {
                temporaryObject.get_roleAssignments().getByPrincipal(self.temporaryPrincipal.principal).deleteObject();
                var collRoleDefinitionBinding = SP.RoleDefinitionBindingCollection.newObject(self.appWebContext);
                for (var num in self.NewRolesCollection) {
                    if (self.NewRolesCollection[num].NotLimittedAcess())
                        collRoleDefinitionBinding.add(self.NewRolesCollection[num].role);
                }
                temporaryObject.get_roleAssignments().add(self.temporaryPrincipal.principal, collRoleDefinitionBinding);
                self.appWebContext.load(self.temporaryPrincipal.principal);
                self.appWebContext.load(temporaryObject);
                self.appWebContext.executeQueryAsync(self.finishAddRoles, self.onError);
            }
            else if(self.NewRolesCollection.length == 0){
                temporaryObject.get_roleAssignments().getByPrincipal(self.temporaryPrincipal.principal).deleteObject();
                self.appWebContext.load(self.temporaryPrincipal.principal);
                self.appWebContext.load(temporaryObject);
                self.appWebContext.executeQueryAsync(self.finishAddRoles, self.onError);
            }


        }

        self.finishAddRoles = function () {
            /*self.sysLoading(true);
            mainself.Wait();
            currentSelection = self.siteCollection()[0];
            currentSelection.itemCollection = currentSelection.site.get_lists();
            self.subSiteCollection = currentSelection.site.get_webs();
            self.appWebContext.load(currentSelection.itemCollection);
            self.appWebContext.load(self.subSiteCollection);
            self.appWebContext.executeQueryAsync(self.onGetSiteInfo, self.onError);*/
            if (self.temporaryObject.type == "List") {
                self.appWebContext.load(self.temporaryObject.listObject, 'RoleAssignments');
                self.appWebContext.load(self.temporaryObject.listObject, 'HasUniqueRoleAssignments');
                self.appWebContext.executeQueryAsync(self.reLoadRoleAssignments, self.onError);
            }
            if (self.temporaryObject.type == "Library") {
                self.appWebContext.load(self.temporaryObject.libraryObject, 'RoleAssignments');
                self.appWebContext.load(self.temporaryObject.libraryObject, 'HasUniqueRoleAssignments');
                self.appWebContext.executeQueryAsync(self.reLoadRoleAssignments, self.onError);
            }
            if (self.temporaryObject.type == "Site") {
                self.appWebContext.load(self.temporaryObject.site, 'RoleAssignments');
                self.appWebContext.load(self.temporaryObject.site, 'HasUniqueRoleAssignments');
                self.appWebContext.executeQueryAsync(self.reLoadRoleAssignments, self.onError);
            }
        }

        self.reLoadRoleAssignments = function () {
            if (self.temporaryObject.type == "List") {
                self.temporaryObject.memberRoleCollection.removeAll();
                self.temporaryObject.hasUniqueRoleAssignment(self.temporaryObject.listObject.get_hasUniqueRoleAssignments());
                var itemEnumerator = self.temporaryObject.listObject.get_roleAssignments().getEnumerator();
                while (itemEnumerator.moveNext()) {
                    self.temporaryObject.memberRoleCollection.push(itemEnumerator.get_current());
                    var length = self.temporaryObject.memberRoleCollection().length;
                    self.appWebContext.load(self.temporaryObject.memberRoleCollection()[length - 1], 'Member');
                    self.appWebContext.load(self.temporaryObject.memberRoleCollection()[length - 1], 'RoleDefinitionBindings');
                }
                self.appWebContext.executeQueryAsync(self.reAssigntValue, self.onError);
            }
            if (self.temporaryObject.type == "Library") {
                self.temporaryObject.memberRoleCollection.removeAll();
                self.temporaryObject.hasUniqueRoleAssignment(self.temporaryObject.libraryObject.get_hasUniqueRoleAssignments());
                var itemEnumerator = self.temporaryObject.libraryObject.get_roleAssignments().getEnumerator();
                while (itemEnumerator.moveNext()) {
                    self.temporaryObject.memberRoleCollection.push(itemEnumerator.get_current());
                    var length = self.temporaryObject.memberRoleCollection().length;
                    self.appWebContext.load(self.temporaryObject.memberRoleCollection()[length - 1], 'Member');
                    self.appWebContext.load(self.temporaryObject.memberRoleCollection()[length - 1], 'RoleDefinitionBindings');
                }
                self.appWebContext.executeQueryAsync(self.reAssigntValue, self.onError);
            }
            if (self.temporaryObject.type == "Site") {
                self.temporaryObject.memberRoleCollection.removeAll();
                self.temporaryObject.hasUniqueRoleAssignment(self.temporaryObject.site.get_hasUniqueRoleAssignments());
                var itemEnumerator = self.temporaryObject.site.get_roleAssignments().getEnumerator();
                while (itemEnumerator.moveNext()) {
                    self.temporaryObject.memberRoleCollection.push(itemEnumerator.get_current());
                    var length = self.temporaryObject.memberRoleCollection().length;
                    self.appWebContext.load(self.temporaryObject.memberRoleCollection()[length - 1], 'Member');
                    self.appWebContext.load(self.temporaryObject.memberRoleCollection()[length - 1], 'RoleDefinitionBindings');
                }
                self.appWebContext.executeQueryAsync(self.reAssigntValueForSubsite, self.onError);
            }
        }
        self.reAssigntValue = function () {
            self.temporaryObject.roleAssignments.removeAll();
            for (var countRole in self.temporaryObject.memberRoleCollection()) {
                var itemEnumerator = self.temporaryObject.memberRoleCollection()[countRole].get_roleDefinitionBindings().getEnumerator();
                self.temporaryObject.roleAssignments.push(new RoleAssignment(self.temporaryObject.memberRoleCollection()[countRole].get_member().get_title()));
                while (itemEnumerator.moveNext()) {
                    var length = self.temporaryObject.roleAssignments().length;
                    self.temporaryObject.roleAssignments()[length - 1].roles.push(itemEnumerator.get_current());
                }
            }
            self.checkGroupandUserEnable();
            self.sysLoading(false);
            self.checkUniqueAssignments();
            mainself.CancelWait();
        }
        self.reAssigntValueForSubsite = function () {
            self.temporaryObject.roleAssignments.removeAll();
            for (var countRole in self.temporaryObject.memberRoleCollection()) {
                var itemEnumerator = self.temporaryObject.memberRoleCollection()[countRole].get_roleDefinitionBindings().getEnumerator();
                self.temporaryObject.roleAssignments.push(new RoleAssignment(self.temporaryObject.memberRoleCollection()[countRole].get_member().get_title()));
                while (itemEnumerator.moveNext()) {
                    var length = self.temporaryObject.roleAssignments().length;
                    self.temporaryObject.roleAssignments()[length - 1].roles.push(itemEnumerator.get_current());
                }
            }
            currentSelection = self.temporaryObject;
            currentSelection.itemCollection = currentSelection.site.get_lists();
            self.subSiteCollection = currentSelection.site.get_webs();
            self.appWebContext.load(currentSelection.itemCollection);
            self.appWebContext.load(self.subSiteCollection);
            self.appWebContext.executeQueryAsync(self.onGetSiteInfo, self.onError);

        }
        self.onCancelChangePermission = function () {
            $("#divChangePermission").hide();
        }
        self.resetRoles = function () {
            for (var num in self.roleCollection()) {
                self.roleCollection()[num].roleEnable(false);
            }
        }
        self.AddNewRole = function (Role) {
            self.NewRolesCollection.push(Role);
        }
        self.checkRoleSimilarity = function (firstRoles, secondRoles) {
            var firstRolesArray = new Array();
            var secondRolesArray = new Array();
            for (var num in firstRoles) {
                firstRolesArray.push(firstRoles[num].get_name());
            }
            for (var num in secondRoles) {
                secondRolesArray.push(secondRoles[num].role.get_name());
            }
            for (var num in firstRolesArray) {
                if (secondRolesArray.indexOf(firstRolesArray[num]) == -1) {
                    return false;
                }
            }
            for (var num in secondRolesArray) {
                if (firstRolesArray.indexOf(secondRolesArray[num]) == -1) {
                    return false;
                }
            }
            return true;
        }

        self.changeInheritance = function (object) {
            self.temporaryObject = object;
            if (self.temporaryObject.type == "List")
                temporaryObject = self.temporaryObject.listObject;
            if (self.temporaryObject.type == "Library")
                temporaryObject = self.temporaryObject.libraryObject;
            if (self.temporaryObject.type == "Site")
                temporaryObject = self.temporaryObject.site;
            if (self.temporaryObject.hasUniqueRoleAssignment()) {
                var r = confirm("You are about to inherit permissions from the parent Web site. Any custom permissions will be lost.");
                if (r == true) {
                    if (PaidVersion == true) {
                        mainself.Wait();
                        self.reInheritance();
                    }
                    else {
                        
                            var r = confirm("You are using the free version, which do not have function to change the permission, would you like to buy our full version for 10 euro?");
                        if (r == true) {
                            window.location.href = 'http://www.arthurgraus.nl/Pages/SharePointPermissionExplorer.aspx';

                        }
                        else {
                        }
                    }
                }
                else {
                }
            }
            else {
                var x = "You are about to create unique permissions for this " + self.temporaryObject.type + ". Changes made to the parent site permissions will no longer affect this " + self.temporaryObject.type + ".";
                var r = confirm(x);
                if (r == true) {
                    if (PaidVersion == true) {
                        mainself.Wait();
                        self.newInheritance();
                    }
                    else {
                        
                            var r = confirm("You are using the free version, which do not have function to change the permission, would you like to buy our full version for 10 euro?");
                        if (r == true) {
                            window.location.href = 'http://www.arthurgraus.nl/Pages/SharePointPermissionExplorer.aspx';

                        }
                        else {
                        }
                    }
                }
                else {
                }
            }
        }
        self.newInheritance = function () {
            temporaryObject.breakRoleInheritance(true,false);
            self.appWebContext.load(temporaryObject);
            self.appWebContext.executeQueryAsync(self.finishAddRoles, self.onError);
        }
        self.reInheritance = function () {
            temporaryObject.resetRoleInheritance();
            self.appWebContext.load(temporaryObject);
            self.appWebContext.executeQueryAsync(self.finishAddRoles, self.onError);
        }

        self.Navigator = function (e) {
            mainself.Wait();
            if (e.libraries().length == 0 && e.lists().length == 0 && e.subSites().length == 0) {
                if (self.sysLoading() == false) {
                    self.sysLoading(true);
                    
                    currentSelection = e;
                    $("#" + String(currentSelection.site.get_id())).show();
                    currentSelection.imgSource(self.imgSource[1]);
                    currentSelection.itemCollection = currentSelection.site.get_lists();
                    self.subSiteCollection = currentSelection.site.get_webs();
                    self.appWebContext.load(currentSelection.itemCollection);
                    self.appWebContext.load(self.subSiteCollection);
                    self.appWebContext.executeQueryAsync(self.onGetSiteInfo, self.onError);
                  
                }
            }
            else if (e.imgSource() == self.imgSource[1]) {
                $("#" + String(e.site.get_id())).hide();
                e.imgSource(self.imgSource[0]);
                mainself.CancelWait();
            }
            else if (e.imgSource() == self.imgSource[0]) {
                $("#" + String(e.site.get_id())).show();
                e.imgSource(self.imgSource[1]);
                mainself.CancelWait();
            } 


        }


        self.checkGroupandUserEnable = function () {
            //mainself.Wait();
            if (self.showGroups()) {
                for (var num in self.principleCollection()) {
                    if (self.principleCollection()[num].type == "Group") {
                        $("#" + String(self.principleCollection()[num].id)).show();
                        $("." + String(self.principleCollection()[num].id)).show();
                    }
                }
            }
            else {
                for (var num in self.principleCollection()) {
                    if (self.principleCollection()[num].type == "Group") {
                        $("#" + String(self.principleCollection()[num].id)).hide();
                        $("." + String(self.principleCollection()[num].id)).hide();
                    }
                }
            }

            if (self.showUsers()) {
                for (var num in self.principleCollection()) {
                    if (self.principleCollection()[num].type == "User") {
                        $("#" + String(self.principleCollection()[num].id)).show();
                        $("." + String(self.principleCollection()[num].id)).show();
                    }
                }
            }
            else {
                for (var num in self.principleCollection()) {
                    if (self.principleCollection()[num].type == "User") {
                        $("#" + String(self.principleCollection()[num].id)).hide();
                        $("." + String(self.principleCollection()[num].id)).hide();
                    }
                }
            }
            //mainself.CancelWait();
            return true;
        }

        self.checkUniqueAssignments = function () {
            if (self.showUniqueAssignments()) {
                for (var num in self.siteCollection()) {
                    for (var numlist in self.siteCollection()[num].lists()) {
                        if (self.siteCollection()[num].lists()[numlist].listObject.get_hasUniqueRoleAssignments()==false) {
                            $("." + String(self.siteCollection()[num].lists()[numlist].id)).hide();
                        }
                    }
                    for (var numlibrary in self.siteCollection()[num].libraries()) {
                        if (self.siteCollection()[num].libraries()[numlibrary].libraryObject.get_hasUniqueRoleAssignments() == false) {
                            $("." + String(self.siteCollection()[num].libraries()[numlibrary].id)).hide();
                        }
                    }
                    for (var numsubsite in self.siteCollection()[num].subSites()) {
                        /*if (self.siteCollection()[num].subSites()[numsubsite].site.get_hasUniqueRoleAssignments() == false) {
                            $("." + String(self.siteCollection()[num].subSites()[numsubsite].site.get_id())).hide();
                        }*/
                        self.checkSubsiteUniqueAssignments(self.siteCollection()[num].subSites()[numsubsite]);
                    }
                }
            }
            else {
                for (var num in self.siteCollection()) {
                    for (var numlist in self.siteCollection()[num].lists()) {
                        if (self.siteCollection()[num].lists()[numlist].listObject.get_hasUniqueRoleAssignments() == false) {
                            $("." + String(self.siteCollection()[num].lists()[numlist].id)).show();
                        }
                    }
                    for (var numlibrary in self.siteCollection()[num].libraries()) {
                        if (self.siteCollection()[num].libraries()[numlibrary].libraryObject.get_hasUniqueRoleAssignments() == false) {
                            $("." + String(self.siteCollection()[num].libraries()[numlibrary].id)).show();
                        }
                    }
                    for (var numsubsite in self.siteCollection()[num].subSites()) {
                        /*if (self.siteCollection()[num].subSites()[numsubsite].site.get_hasUniqueRoleAssignments() == false) {
                            $("." + String(self.siteCollection()[num].subSites()[numsubsite].site.get_id())).show();
                        }*/
                        self.checkSubsiteUniqueAssignments(self.siteCollection()[num].subSites()[numsubsite]);
                    }
                }
            }
            return true;
        }

        self.checkSubsiteUniqueAssignments = function (Subsite) {
            if (self.showUniqueAssignments()) {
                for (var numlist in Subsite.lists()) {
                    if (Subsite.lists()[numlist].listObject.get_hasUniqueRoleAssignments() == false) {
                        $("." + String(Subsite.lists()[numlist].id)).hide();
                    }
                }
                for (var numlibrary in Subsite.libraries()) {
                    if (Subsite.libraries()[numlibrary].libraryObject.get_hasUniqueRoleAssignments() == false) {
                        $("." + String(Subsite.libraries()[numlibrary].id)).hide();
                    }
                }
                for (var numsubsite in Subsite.subSites()) {
                    /*if (self.siteCollection()[num].subSites()[numsubsite].site.get_hasUniqueRoleAssignments() == false) {
                        $("." + String(self.siteCollection()[num].subSites()[numsubsite].site.get_id())).hide();
                    }*/
                    self.checkSubsiteUniqueAssignments(Subsite.subSites()[numsubsite]);
                }
            }
            else {
                for (var numlist in Subsite.lists()) {
                    if (Subsite.lists()[numlist].listObject.get_hasUniqueRoleAssignments() == false) {
                        $("." + String(Subsite.lists()[numlist].id)).show();
                    }
                }
                for (var numlibrary in Subsite.libraries()) {
                    if (Subsite.libraries()[numlibrary].libraryObject.get_hasUniqueRoleAssignments() == false) {
                        $("." + String(Subsite.libraries()[numlibrary].id)).show();
                    }
                }
                for (var numsubsite in Subsite.subSites()) {
                    /*if (self.siteCollection()[num].subSites()[numsubsite].site.get_hasUniqueRoleAssignments() == false) {
                        $("." + String(self.siteCollection()[num].subSites()[numsubsite].site.get_id())).show();
                    }*/
                    self.checkSubsiteUniqueAssignments(Subsite.subSites()[numsubsite]);
                }
            }
        }

        self.onCheckAll = function () {
            //mainself.Wait();
            self.checkGroupandUserEnable();
            self.checkUniqueAssignments();
            //mainself.CancelWait();
        }

        self.onGetSiteInfo = function () {
            valueLoading = true;
            var listsAndLibraries = [];
            var subsites = []
            var itemEnumerator = currentSelection.itemCollection.getEnumerator();
            currentSelection.softedItemCollection = [];
            while (itemEnumerator.moveNext()) {
                currentSelection.softedItemCollection.push(itemEnumerator.get_current());
                listsAndLibraries.push(itemEnumerator.get_current());
            }
            itemEnumerator = self.subSiteCollection.getEnumerator();
            while (itemEnumerator.moveNext()) {
                if (itemEnumerator.get_current().get_webTemplate() != 'APP') {
                    currentSelection.softedItemCollection.push(itemEnumerator.get_current());
                    subsites.push(itemEnumerator.get_current())
                }
            }
            listsAndLibraries.sort(function (a, b) {
                var nameA = String(a.get_title()).toLowerCase(), nameB = String(b.get_title()).toLowerCase();
                if (nameA < nameB)
                    return -1;
                if (nameA > nameB)
                    return 1;
                return 0;
            });
            subsites.sort(function (a, b) {
                var nameA = String(a.get_title()).toLowerCase(), nameB = String(b.get_title()).toLowerCase();
                if (nameA < nameB)
                    return -1;
                if (nameA > nameB)
                    return 1;
                return 0;
            });

            currentSelection.collectionCount = currentSelection.softedItemCollection.length;
            if (currentSelection.lists().length > 0) {
                //for (var num in currentSelection.lists())
                    currentSelection.lists.removeAll();
            }
            if (currentSelection.libraries().length > 0) {
                //for (var num in currentSelection.libraries())
                    currentSelection.libraries.removeAll();
            }
            if (currentSelection.subSites().length > 0) {
                //for (var num in currentSelection.subSites())
                    currentSelection.subSites.removeAll();
            }
            for (var count in listsAndLibraries) {
                if (listsAndLibraries[count].get_baseType() == 0) {
                    currentSelection.lists.push(new List(listsAndLibraries[count]));
                }
                else {
                    currentSelection.libraries.push(new Library(listsAndLibraries[count]));
                }
            }
            for (var count in subsites) {
                currentSelection.subSites.push(new Site(subsites[count], self.imgSource[0]));
            }
            self.onGetRoleAssignment();

        }
        self.onGetRoleAssignment = function () {
            currentSelection.collectionCount = 3;
            for (var count in currentSelection.lists()) {
                self.appWebContext.load(currentSelection.lists()[count].listObject, 'RoleAssignments');
                self.appWebContext.load(currentSelection.lists()[count].listObject, 'HasUniqueRoleAssignments');
                //self.checkGroupandUserEnable();
                //self.appWebContext.executeQueryAsync(self.onGetMemberAndRole, self.onError);
            }
            self.appWebContext.executeQueryAsync(self.onGetMemberAndRole, self.onError);
            for (var count in currentSelection.libraries()) {
                self.appWebContext.load(currentSelection.libraries()[count].libraryObject, 'RoleAssignments');
                self.appWebContext.load(currentSelection.libraries()[count].libraryObject, 'HasUniqueRoleAssignments');
                //self.checkGroupandUserEnable();
                //self.appWebContext.executeQueryAsync(self.onGetMemberAndRole, self.onError);
            }
            self.appWebContext.executeQueryAsync(self.onGetMemberAndRole, self.onError);
            for (var count in currentSelection.subSites()) {
                self.appWebContext.load(currentSelection.subSites()[count].site, 'RoleAssignments');
                self.appWebContext.load(currentSelection.subSites()[count].site, 'HasUniqueRoleAssignments');
                //self.checkGroupandUserEnable();
                //self.appWebContext.executeQueryAsync(self.onGetMemberAndRole, self.onError);
            }
            self.appWebContext.executeQueryAsync(self.onGetMemberAndRole, self.onError);

        }
        self.onGetMemberAndRole = function () {
            currentSelection.collectionCount--;
            if (currentSelection.collectionCount == 0) {
                //self.checkUniqueAssignments();
                //self.checkGroupandUserEnable();
                for (var count in currentSelection.lists()) {
                    if (currentSelection.lists()[count].memberRoleCollection().length > 0) {
                        //for (var num in currentSelection.lists()[count].memberRoleCollection())
                        //currentSelection.lists()[count].memberRoleCollection().pop();
                        currentSelection.lists()[count].memberRoleCollection.removeAll();
                    }
                    currentSelection.lists()[count].hasUniqueRoleAssignment(currentSelection.lists()[count].listObject.get_hasUniqueRoleAssignments());
                    var itemEnumerator = currentSelection.lists()[count].listObject.get_roleAssignments().getEnumerator();
                    while (itemEnumerator.moveNext()) {
                        currentSelection.collectionCount++;
                    }
                    itemEnumerator = currentSelection.lists()[count].listObject.get_roleAssignments().getEnumerator();
                    while (itemEnumerator.moveNext()) {
                        currentSelection.lists()[count].memberRoleCollection.push(itemEnumerator.get_current());
                        var length = currentSelection.lists()[count].memberRoleCollection().length;
                        self.appWebContext.load(currentSelection.lists()[count].memberRoleCollection()[length-1], 'Member');
                        self.appWebContext.load(currentSelection.lists()[count].memberRoleCollection()[length - 1], 'RoleDefinitionBindings');
                        self.appWebContext.executeQueryAsync(self.AssigntValue, self.onError);
                    }
                }
                for (var count in currentSelection.libraries()) {
                    if (currentSelection.libraries()[count].memberRoleCollection().length > 0) {
                        //for (var num in currentSelection.libraries()[count].memberRoleCollection())
                        //  currentSelection.libraries()[count].memberRoleCollection().pop();
                        currentSelection.libraries()[count].memberRoleCollection.removeAll();

                    }
                    currentSelection.libraries()[count].hasUniqueRoleAssignment(currentSelection.libraries()[count].libraryObject.get_hasUniqueRoleAssignments());
                    var itemEnumerator = currentSelection.libraries()[count].libraryObject.get_roleAssignments().getEnumerator();
                    while (itemEnumerator.moveNext()) {
                        currentSelection.collectionCount++;
                    }
                    itemEnumerator = currentSelection.libraries()[count].libraryObject.get_roleAssignments().getEnumerator();
                    while (itemEnumerator.moveNext()) {
                        currentSelection.libraries()[count].memberRoleCollection.push(itemEnumerator.get_current());
                        var length = currentSelection.libraries()[count].memberRoleCollection().length;
                        self.appWebContext.load(currentSelection.libraries()[count].memberRoleCollection()[length-1], 'Member');
                        self.appWebContext.load(currentSelection.libraries()[count].memberRoleCollection()[length - 1], 'RoleDefinitionBindings');
                        self.appWebContext.executeQueryAsync(self.AssigntValue, self.onError);
                    }
                }
                for (var count in currentSelection.subSites()) {
                    if (currentSelection.subSites()[count].memberRoleCollection().length > 0) {
                        //for (var num in currentSelection.subSites()[count].memberRoleCollection())
                        //    currentSelection.subSites()[count].memberRoleCollection().pop();
                        currentSelection.subSites()[count].memberRoleCollection.removeAll();
                    }
                    currentSelection.subSites()[count].hasUniqueRoleAssignment(currentSelection.subSites()[count].site.get_hasUniqueRoleAssignments());
                    var itemEnumerator = currentSelection.subSites()[count].site.get_roleAssignments().getEnumerator();
                    while (itemEnumerator.moveNext()) {
                        currentSelection.collectionCount++;
                    }
                    itemEnumerator = currentSelection.subSites()[count].site.get_roleAssignments().getEnumerator();
                    while (itemEnumerator.moveNext()) {
                        currentSelection.subSites()[count].memberRoleCollection.push(itemEnumerator.get_current());
                        var length = currentSelection.subSites()[count].memberRoleCollection().length;
                        self.appWebContext.load(currentSelection.subSites()[count].memberRoleCollection()[length - 1], 'Member');
                        self.appWebContext.load(currentSelection.subSites()[count].memberRoleCollection()[length - 1], 'RoleDefinitionBindings');
                        self.appWebContext.executeQueryAsync(self.AssigntValue, self.onError);
                    }
                }
                valueLoading = false;
            }
        }
        self.AssigntValue = function () {
            currentSelection.collectionCount--;
            if (currentSelection.collectionCount == 0 && valueLoading == false) {
                currentSelection.collectionCount = currentSelection.softedItemCollection.length;
                for (var count in currentSelection.lists()) {
                    if (currentSelection.lists()[count].roleAssignments().length > 0) {
                        //for (var num in currentSelection.lists()[count].roleAssignments())
                        //    currentSelection.lists()[count].roleAssignments().pop();
                        currentSelection.lists()[count].roleAssignments().removeAll();
                    }
                    for (var countRole in currentSelection.lists()[count].memberRoleCollection()) {
                        var itemEnumerator = currentSelection.lists()[count].memberRoleCollection()[countRole].get_roleDefinitionBindings().getEnumerator();
                        currentSelection.lists()[count].roleAssignments.push(new RoleAssignment(currentSelection.lists()[count].memberRoleCollection()[countRole].get_member().get_title()));
                        while (itemEnumerator.moveNext()) {
                            var length = currentSelection.lists()[count].roleAssignments().length;
                            currentSelection.lists()[count].roleAssignments()[length - 1].roles.push(itemEnumerator.get_current());
                        }
                    }
                }
                for (var count in currentSelection.libraries()) {
                    if (currentSelection.libraries()[count].roleAssignments().length > 0) {
                        //for (var num in currentSelection.libraries()[count].roleAssignments())
                        //    currentSelection.libraries()[count].roleAssignments().pop();
                        currentSelection.libraries()[count].roleAssignments.removeAll();
                    }
                    for (var countRole in currentSelection.libraries()[count].memberRoleCollection()) {
                        var itemEnumerator = currentSelection.libraries()[count].memberRoleCollection()[countRole].get_roleDefinitionBindings().getEnumerator();
                        currentSelection.libraries()[count].roleAssignments.push(new RoleAssignment(currentSelection.libraries()[count].memberRoleCollection()[countRole].get_member().get_title()));
                        while (itemEnumerator.moveNext()) {
                            var length = currentSelection.libraries()[count].roleAssignments().length;
                            currentSelection.libraries()[count].roleAssignments()[length - 1].roles.push(itemEnumerator.get_current());
                        }
                    }
                }
                for (var count in currentSelection.subSites()) {
                    if (currentSelection.subSites()[count].roleAssignments().length > 0) {
                        //for (var num in currentSelection.subSites()[count].roleAssignments())
                        //    currentSelection.subSites()[count].roleAssignments().pop();
                        currentSelection.subSites()[count].roleAssignments.removeAll();
                    }
                    for (var countRole in currentSelection.subSites()[count].memberRoleCollection()) {
                        var itemEnumerator = currentSelection.subSites()[count].memberRoleCollection()[countRole].get_roleDefinitionBindings().getEnumerator();
                        currentSelection.subSites()[count].roleAssignments.push(new RoleAssignment(currentSelection.subSites()[count].memberRoleCollection()[countRole].get_member().get_title()));
                        while (itemEnumerator.moveNext()) {
                            var length = currentSelection.subSites()[count].roleAssignments().length;
                            currentSelection.subSites()[count].roleAssignments()[length - 1].roles.push(itemEnumerator.get_current());
                        }
                    }
                }
                
                
                self.sysLoading(false);
                self.checkGroupandUserEnable();
                self.checkUniqueAssignments();
                mainself.CancelWait();
            }
        }


    }

    
};


function getQueryStringParameter(paramToRetrieve) {
    var params =
        document.URL.split("?")[1].split("&");
    var strParams = "";
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    }
}